import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

const getOption = (titleName) => ({
  tooltip: {
    trigger: 'item',
  },
  title: {
    text: titleName,
    right: 'center',
    bottom: '0',
    textStyle: {
      color: '#ce0e2d',
    },
  },
  legend: {
    show: false,
  },
  series: [
    {
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        color(params) {
          // 自定义颜色数组
          const colorList = ['#767CE0', '#0095FF', '#00C6FF', '#40E3E4', '#5FD7C3'];
          return colorList[params.dataIndex];
        },
      },
      // center: ['25%', '50%'],
      label: {
        normal: {
          show: true,
          formatter() {
            return '{a|总销量}\n{b|9930}';
          },
          position: 'center',
          rich: {
            a: {
              color: '#ccc',
              fontSize: 12,
              padding: [2, 0],
              borderRadius: 100,
            },
            b: {
              fontSize: 20,
              padding: [2, 0],
              borderRadius: 100,
            },
          },
        },
      },
      emphasis: {
        label: {},
      },
      labelLine: {
        show: false,
      },
      data: [
        { value: 1233, name: '超高端' },
        { value: 759, name: '高端' },
        { value: 3555, name: '中高端' },
        { value: 134, name: '中低端' },
      ],
    },
  ],
});

export const EchartsPie = (props) => {
  console.log(props, 'propspropsprops====');

  const chartRef = useRef(null);

  useEffect(() => {
    const chartDom = chartRef.current;
    const myChart = echarts.init(chartDom);
    myChart.clear();
    const option = getOption(props.name);
    myChart.setOption(option);

    return () => {
      myChart.dispose(); // 在组件卸载时清理echarts实例
    };
  }, [props.name]);

  return (
    <div style={{ margin: '0 auto', flexShrink: 0 }}>
      <div ref={chartRef} style={{ height: '180px', paddingBottom: '10px' }} />
    </div>
  );
};
